from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import jwt
import datetime
import json
import os
from functools import wraps

app = Flask(__name__)
CORS(app)

# 配置
SECRET_KEY = 'your-secret-key'  # 请修改为安全的密钥
ADMIN_USERNAME = 'admin'
ADMIN_PASSWORD = 'admin123'  # 请修改为安全的密码

# 数据存储
SIGNS_FILE = 'signs.json'

def load_signs():
    if os.path.exists(SIGNS_FILE):
        with open(SIGNS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return []

def save_signs(signs):
    with open(SIGNS_FILE, 'w', encoding='utf-8') as f:
        json.dump(signs, f, ensure_ascii=False, indent=2)

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'success': False, 'message': '缺少认证令牌'}), 401
        
        try:
            token = token.split(' ')[1]
            data = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
            if data['username'] != ADMIN_USERNAME:
                return jsonify({'success': False, 'message': '无效的认证令牌'}), 401
        except:
            return jsonify({'success': False, 'message': '无效的认证令牌'}), 401
        
        return f(*args, **kwargs)
    return decorated

@app.route('/api/admin/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    if username == ADMIN_USERNAME and password == ADMIN_PASSWORD:
        token = jwt.encode({
            'username': username,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)
        }, SECRET_KEY)
        return jsonify({'success': True, 'token': token})
    
    return jsonify({'success': False, 'message': '用户名或密码错误'}), 401

@app.route('/api/admin/signs', methods=['GET'])
@token_required
def get_signs():
    signs = load_signs()
    return jsonify({'success': True, 'signs': signs})

@app.route('/api/admin/signs', methods=['POST'])
@token_required
def add_sign():
    data = request.get_json()
    signs = load_signs()
    
    new_sign = {
        'id': str(len(signs) + 1),
        'name': data['name'],
        'signInId': data['signInId'],
        'startTime': data['startTime'],
        'endTime': data['endTime'],
        'refreshInterval': data['refreshInterval']
    }
    
    signs.append(new_sign)
    save_signs(signs)
    
    return jsonify({'success': True, 'sign': new_sign})

@app.route('/api/admin/signs/<sign_id>', methods=['DELETE'])
@token_required
def delete_sign(sign_id):
    signs = load_signs()
    signs = [sign for sign in signs if sign['id'] != sign_id]
    save_signs(signs)
    return jsonify({'success': True})

@app.route('/api/signs/current', methods=['GET'])
def get_current_sign():
    signs = load_signs()
    current_time = datetime.datetime.now().timestamp() * 1000
    
    for sign in signs:
        if sign['startTime'] <= current_time <= sign['endTime']:
            return jsonify({
                'success': True,
                'sign': sign
            })
    
    return jsonify({'success': False, 'message': '当前没有活动的签到'})

@app.route('/')
def index():
    return send_from_directory('.', 'sign.html')

@app.route('/admin_login.html')
def admin_login():
    return send_from_directory('.', 'admin_login.html')

@app.route('/admin/config.html')
def admin_config():
    return send_from_directory('.', 'admin_config.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5500, debug=True) 